package com.buric.common.interceptor;

import com.buric.common.annontation.Pass;
import com.buric.common.constant.ContextConstants;
import com.buric.common.constant.TokenConstants;
import com.buric.common.exception.NotLoginException;
import com.buric.common.utils.ContextHolder;
import com.buric.common.utils.ServletUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @author: zhou.wei
 * @description 请求头拦截器
 * @date: 2024/5/9 14:18
 */
public class HeaderInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {

        String token = ServletUtils.getHeader(request, TokenConstants.TOKEN);

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Pass methodPass = ((HandlerMethod) handler).getMethod().getAnnotation(Pass.class);
        Pass typeNoAuth = ((HandlerMethod) handler).getBeanType().getAnnotation(Pass.class);
        if(methodPass == null || typeNoAuth == null){
             String userId = ServletUtils.getHeader(request, ContextConstants.USER_ID);
             if(userId == null || token == null){
                 throw new NotLoginException("请重新登录");
             }
        }
        Optional.ofNullable(ServletUtils.getHeader(request, ContextConstants.USER_ID)).ifPresent(a -> ContextHolder.set(ContextConstants.USER_ID, a));
        Optional.ofNullable(ServletUtils.getHeader(request, ContextConstants.USER_NAME)).ifPresent(a -> ContextHolder.set(ContextConstants.USER_NAME, a));
        Optional.ofNullable(ServletUtils.getHeader(request, ContextConstants.CHANNEL_TYPE)).ifPresent(a -> ContextHolder.set(ContextConstants.CHANNEL_TYPE, a));
        Optional.ofNullable(ServletUtils.getHeader(request, ContextConstants.ROLE_PERMISSION)).ifPresent(a -> ContextHolder.set(ContextConstants.ROLE_PERMISSION, a));
        return true;
    }


    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHolder.remove();
    }
}
